﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class ajax_addreviewwork : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["id_user"] != null && Session["permission"] != null
            && (((int)Session["permission"]) >= 2))
        {
            try
            {
                int userId = Int32.Parse(Session["id_user"].ToString());
                int workId = Int32.Parse(Request["id"]);
                string sql = "SELECT projectId,status,catId FROM work WHERE id=" + comm.to_sql(workId.ToString(), "number");
                DataTable dtTable = dal.SelectTable(sql);
                int projectId = 0;
                int oldStatus = 1;
                int catId = 0;
                if (dtTable.Rows.Count == 1)
                {
                    projectId = Int32.Parse(dtTable.Rows[0]["projectId"].ToString());
                    oldStatus = Int32.Parse(dtTable.Rows[0]["status"].ToString());
                    catId = Int32.Parse(dtTable.Rows[0]["catId"].ToString());
                }
                else
                    throw new Exception("FAIL");

                #region check user is enable to access this project
                SqlParameter[] listParams = new SqlParameter[3];
                //-- param 1: @userId
                SqlParameter param = new SqlParameter("@userId", userId);
                param.SqlDbType = SqlDbType.Int;
                param.Direction = ParameterDirection.Input;
                listParams[0] = param;

                //-- param 2: @projectId
                param = new SqlParameter("@projectId", projectId);
                param.SqlDbType = SqlDbType.Int;
                param.Direction = ParameterDirection.Input;
                listParams[1] = param;

                //-- param 3: @isAccess
                param = new SqlParameter();
                param.ParameterName = "@isAccess";
                param.SqlDbType = SqlDbType.Int;
                param.Direction = ParameterDirection.Output;
                listParams[2] = param;

                dal.ExecuteSP("proCheckAccessProject_GET", listParams);
                int enable = Int32.Parse(listParams[2].Value.ToString());
                if (enable == 0)
                    throw new Exception("FAIL");
                #endregion

                #region check leader is enable to note work to project
                if (((int)Session["permission"]) >= 4)
                {
                    sql = " SELECT permission FROM UserProject " +
                          " WHERE userId=" + comm.to_sql(userId.ToString(), "number") +
                          " AND projectId=" + comm.to_sql(projectId.ToString(), "number");
                    dtTable = dal.SelectTable(sql);
                    if (dtTable.Rows.Count == 1)
                    {
                        int permission = Int32.Parse(dtTable.Rows[0]["permission"].ToString());
                        if (permission >= 5)
                        {
                            sql = "SELECT userId FROM work WHERE id=" + comm.to_sql(workId.ToString(), "number");
                            dtTable = dal.SelectTable(sql);
                            if (dtTable.Rows.Count == 1)
                            {
                                int userworkId = Int32.Parse(dtTable.Rows[0]["userId"].ToString());
                                if (userId != userworkId)
                                    throw new Exception("FAIL");
                            }
                            else
                                throw new Exception("FAIL");
                        }
                    }
                    else
                        throw new Exception("FAIL");
                }
                #endregion

                #region add note and change status to work
                int status = Int32.Parse(Request["status"]);
                string note = comm.StandardString(Request["note"]);
                note = note.Replace("\n","<br/>");
                // update status
                sql = " UPDATE work " +
                      " SET status=" + comm.to_sql(status.ToString(), "number") +
                      " WHERE id=" + comm.to_sql(workId.ToString(), "number");

                if (dal.Execute(sql) == 1)
                {
                    // update completepercent
                    if (oldStatus != status)
                    {
                        SqlParameter[] someParams = new SqlParameter[2];
                        //-- param 1: @catId

                        param = new SqlParameter("@catId", catId);
                        param.SqlDbType = SqlDbType.Int;
                        param.Direction = ParameterDirection.Input;
                        someParams[0] = param;

                        //-- param 2: @projectId
                        param = new SqlParameter("@projectId", projectId);
                        param.SqlDbType = SqlDbType.Int;
                        param.Direction = ParameterDirection.Input;
                        someParams[1] = param;

                        dal.ExecuteSP("proUpdatePercentProjectCat_EXE", someParams);
                    }
                    // add a new note
                    if (note.Length > 0)
                    {
                        string date = comm.GetCurrentDay() + "/" + comm.GetCurrentMonth() + "/" + comm.GetCurrentYear();
                        sql = " INSERT INTO note(userId,workId,[content],date)" +
                            " VALUES(" + comm.to_sql(userId.ToString(), "number") + "," + comm.to_sql(workId.ToString(), "number") +
                            "," + comm.to_sql(note, "string") + "," + comm.to_sql(date, "date") + ")";
                        dal.Execute(sql);
                    }

                    #region send mail ----------------------------------------------------------------
                    // get userId of current work
                    int idUser = 0;
                    int idLeader = 0;
                    string content = "";
                    sql = "SELECT userId,leaderId,[content] FROM work WHERE id =" + comm.to_sql(workId.ToString(), "number");
                    dtTable = dal.SelectTable(sql);
                    if (dtTable.Rows.Count == 1)
                    {
                        idUser = Int32.Parse(dtTable.Rows[0]["userId"].ToString());
                        idLeader = Int32.Parse(dtTable.Rows[0]["leaderId"].ToString());
                        content = dtTable.Rows[0]["content"].ToString();
                    }
                    
                    // send mail cho user
                    if (idUser != userId && idUser != 0)
                    {
                        sql = "SELECT email,mailwhencomment FROM [user] WHERE id=" + comm.to_sql(idUser.ToString(), "number");
                        dtTable = dal.SelectTable(sql);
                        if (dtTable.Rows.Count == 1)
                        {
                            string email = dtTable.Rows[0]["email"].ToString();
                            string mailwhenwork = dtTable.Rows[0]["mailwhencomment"].ToString().ToLower();
                            string mailcontent = "Công việc \" " + content + " \" vừa được đánh giá ! Hãy vào http://localhost/workmanagement để kiểm tra !";
                            if (mailwhenwork == "true")
                            {
                                comm.SendMail("idt2010.vn@gmail.com", email, "Đánh giá công việc", mailcontent);
                            }
                        }

                    }
                    //throw new Exception("send mail");
                    // send mail cho leader
                    if (idLeader != userId && idLeader != 0)
                    {
                        sql = "SELECT email,mailwhencomment FROM [user] WHERE id=" + comm.to_sql(idLeader.ToString(), "number");
                        dtTable = dal.SelectTable(sql);
                        if (dtTable.Rows.Count == 1)
                        {
                            string email = dtTable.Rows[0]["email"].ToString();
                            string mailwhenwork = dtTable.Rows[0]["mailwhencomment"].ToString().ToLower();
                            string mailcontent = "Công việc \" " + content + " \" vừa được đánh giá ! Hãy vào http://localhost/workmanagement để kiểm tra !";
                            if (mailwhenwork == "true")
                            {
                                comm.SendMail("idt2010.vn@gmail.com", email, "Đánh giá công việc", mailcontent);
                            }
                        }
                    }
                    #endregion
                    throw new Exception("OK");
                }
                else
                    throw new Exception("FAIL");
                #endregion
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }
}
